﻿#include "DlgReportDay.h"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/msgdlg.h>
#include <wx/valtext.h>
//wxFreeChart头文件
#include "wx/wxfreechartdefs.h"
#include <wx/xy/xyplot.h>
#include <wx/xy/xylinerenderer.h>
#include <wx/xy/xysimpledataset.h>
#include <wx/axis/logarithmicnumberaxis.h>
#include "TimeSeriesDataset.h"

//(*InternalHeaders(DlgUser)
#include <wx/intl.h>
#include <wx/string.h>
//*)

//(*IdInit(DlgUser)
//*)
const wxString WINDOWS_TEXT = _T("日生活报表");
//控件ID
const long CDlgReportDay::IDC_BTN_EXIT= wxNewId();
const long CDlgReportDay::IDC_BTN_SEARCH= wxNewId();
const long CDlgReportDay::IDC_COMBO_SEARCH= wxNewId();
const long CDlgReportDay::IDC_EDIT_SEARCH= wxNewId();
const long CDlgReportDay::IDC_LIST= wxNewId();
const long CDlgReportDay::IDC_TIMEFROM= wxNewId();
const long CDlgReportDay::IDC_TIMETO= wxNewId();
const long CDlgReportDay::IDC_EDIT_STATIC= wxNewId();
const long CDlgReportDay::IDC_PIC= wxNewId();
const long CDlgReportDay::IDC_TIMER_SEC= wxNewId();

BEGIN_EVENT_TABLE(CDlgReportDay,wxDialog)
    //(*EventTable(DlgUser)
    //*)
END_EVENT_TABLE()

CDlgReportDay::CDlgReportDay(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
    :m_Sectimer(this,IDC_TIMER_SEC)
{
    //(*Initialize(DlgUser)
    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxMAXIMIZE_BOX|wxMINIMIZE_BOX, _T("id"));
    SetClientSize(wxDefaultSize);
    Move(wxDefaultPosition);
    //*)
    SetTitle(WINDOWS_TEXT);
    SetWindowStyle(GetWindowStyle()|wxRESIZE_BORDER|wxCLOSE_BOX|wxMAXIMIZE_BOX|wxMINIMIZE_BOX);
    CreateCtrlAndEvent();
    InitComboBoxAndListCtrl();
}

CDlgReportDay::~CDlgReportDay()
{
    //(*Destroy(DlgUser)
    //*)
}

void CDlgReportDay::CreateCtrlAndEvent()
{
    /////////创建控件并布局
    topSizer_=new wxBoxSizer(wxVERTICAL);//顶层窗口布局,从上到下包含每个了窗口布局
    wxFlexGridSizer *fir_secSize=new wxFlexGridSizer(1,2,0,0);
    fir_secSize->AddGrowableCol(0);
    wxBoxSizer *fir_secSize_l=new wxBoxSizer(wxVERTICAL);

    wxBoxSizer *firSize=new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer *secSize=new wxBoxSizer(wxHORIZONTAL);
    wxGridSizer *fifSize=new wxGridSizer(2);
    wxStaticBox* staticBox=new wxStaticBox(this,wxID_ANY,wxT("统计信息"));
    wxStaticBoxSizer *sixSize=new wxStaticBoxSizer(staticBox,wxHORIZONTAL);
    wxBoxSizer *bottomSize=new wxBoxSizer(wxHORIZONTAL);
    topSizer_->Add(fir_secSize,0,wxEXPAND|wxALL,0);
    topSizer_->Add(fifSize,10,wxEXPAND|wxALL,0);
    topSizer_->Add(sixSize,3,wxEXPAND|wxALL,0);
    topSizer_->Add(bottomSize,0,wxEXPAND|wxALL,0);

    combo_search_=new wxChoice(this,IDC_COMBO_SEARCH);
    btn_Exit_=new wxButton(this,IDC_BTN_EXIT,_T("退出"));
    btn_Search_=new wxButton(this,IDC_BTN_SEARCH,_T("查询"));
    text_search_=new wxTextCtrl(this,IDC_EDIT_SEARCH,wxEmptyString);
    list_=new wxListCtrl(this,IDC_LIST,wxDefaultPosition,wxDefaultSize,wxLC_REPORT|wxLC_SINGLE_SEL);
    timeto_=new wxDatePickerCtrl(this,IDC_TIMETO,wxDefaultDateTime,wxDefaultPosition,
                                 wxDefaultSize,wxDP_DROPDOWN|wxDP_SHOWCENTURY);
    timefrom_=new wxDatePickerCtrl(this,IDC_TIMEFROM,wxDefaultDateTime,wxDefaultPosition,
                                   wxDefaultSize,wxDP_DROPDOWN|wxDP_SHOWCENTURY);
    text_stat_=new wxTextCtrl(this,IDC_EDIT_STATIC,wxEmptyString,
                              wxDefaultPosition,wxSize(600,100),wxTE_PROCESS_ENTER|wxTE_MULTILINE|wxHSCROLL);
    chartpanel_=new wxChartPanel(this,IDC_PIC,NULL,wxDefaultPosition,wxDefaultSize);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("从")),1, wxTILE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(timefrom_,1, wxEXPAND|wxALL|wxALIGN_CENTER,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("到")),1, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(timeto_,1, wxFIXED_MINSIZE|wxALL|wxALIGN_LEFT,5);
    secSize->Add(new wxStaticText(this,wxID_ANY,_T("查询类别")),1, wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(combo_search_,1, wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize->Add(text_search_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    fir_secSize_l->Add(firSize,5,wxTILE|wxALL|wxALIGN_CENTER,5);
    fir_secSize_l->Add(secSize,5,wxEXPAND|wxALL,5);
    fir_secSize->Add(fir_secSize_l,10,wxEXPAND|wxALL|wxALIGN_CENTER,0);
    fir_secSize->Add(btn_Search_,0,wxEXPAND|wxALL|wxALIGN_CENTER,0);
    fifSize->Add(list_,1,wxEXPAND | wxALL,5);
    fifSize->Add(chartpanel_,1,wxEXPAND | wxALL,5);
    sixSize->Add(text_stat_,1,wxEXPAND | wxALL,5);

    bottomSize->Add(btn_Exit_,1,wxTILE|wxALL|wxALIGN_CENTER,5);

    SetSizer(topSizer_);//绑定对话框和布局控件
    SetAutoLayout(true);
    topSizer_->Fit(this);//调用对话框大小
    topSizer_->SetSizeHints(this);//设置对话框最小大小

    ///////创建事件
    Connect(IDC_BTN_EXIT,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgReportDay::OnBnClickedBtnExit);
    Connect(IDC_BTN_SEARCH,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgReportDay::OnBnClickedBtnSearch);
    Connect( wxEVT_TIMER, (wxObjectEventFunction)&CDlgReportDay::OnTimer);
    m_Sectimer.Start(1000);

    wxLogDebug(_T("CreateCtrl"));
}

void CDlgReportDay::InitComboBoxAndListCtrl()
{
    wxChoice *pchoice=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->SetSingleStyle(wxLC_REPORT);
    pList->SetSingleStyle(wxLC_SINGLE_SEL);
    pList->InsertColumn(pList->GetColumnCount(),_T("日期"),wxLIST_FORMAT_LEFT,wxLIST_AUTOSIZE);
    pList->InsertColumn(pList->GetColumnCount(),_T("收支数"),wxLIST_FORMAT_LEFT,wxLIST_AUTOSIZE);
    const vector<pair<wxString,wxString> >&chs_fileds_name=GetFiled_CHS_Name(_T("name_VcashFull"));
    auto it=chs_fileds_name.cbegin();
    for (; it!=chs_fileds_name.cend(); ++it) {
        wxLogDebug(_T("%s "),it->first);
        pchoice->Append(it->first);
    }
    wxDateTime cur_time=wxDateTime::Now();
    cur_time.SetDay(1);//设为1号
    wxDatePickerCtrl *pDT=wxDynamicCast(FindWindowById(IDC_TIMEFROM),wxDatePickerCtrl);
    pDT->SetValue(cur_time);
    cur_time.Add(wxDateSpan::Month());//加一个月
    cur_time.Subtract(wxDateSpan::Day());//减一天，即为当月最后一天
    pDT=wxDynamicCast(FindWindowById(IDC_TIMETO),wxDatePickerCtrl);
    pDT->SetValue(cur_time);
    wxLogDebug(_T("InitComboBoxAndListCtrl"));
}

void CDlgReportDay::OnBnClickedBtnSearch(wxCommandEvent& event)
{
    wxBusyCursor waticursor;
    wxChoice *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    int index=pBox->GetSelection();
    wxString strComboTextFirst,strComboTextSecond;
    if (index != wxNOT_FOUND) {
        strComboTextFirst=pBox->GetString(index);
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->DeleteAllItems();
    wxDatePickerCtrl *pDT=wxDynamicCast(FindWindowById(IDC_TIMETO),wxDatePickerCtrl);
    wxString time_to=pDT->GetValue().FormatISODate();
    pDT=wxDynamicCast(FindWindowById(IDC_TIMEFROM),wxDatePickerCtrl);
    wxString time_from=pDT->GetValue().FormatISODate();
    const vector<pair<wxString,wxString> >&chs_filed_name=GetFiled_CHS_Name(_T("name_VcashFull"));
    if (chs_filed_name.empty()) {
        return;
    }
    auto it=chs_filed_name.cbegin();
    for (; it!=chs_filed_name.cend(); ++it) {
        if (strComboTextFirst==it->first) {
            strComboTextSecond=it->second;
            break;
        }
    }
    wxString expendsql=_T("select theDay,sum(balance) as balance from VcashFull  where date(theDay) >=date(@pa1) ")
                       _T(" and date(theDay) <=date(@pa2) ");
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_SEARCH),wxTextCtrl);
    wxString csEditText=pText->GetValue();
    csEditText.Trim(true);
    csEditText.Trim(false);
    if (!csEditText.IsEmpty() && !strComboTextFirst.IsEmpty()) {
        expendsql+=_T(" and ")+strComboTextSecond;
        expendsql+=_T(" like  '%")+csEditText+_T("%'");
    }
    expendsql+=_T(" group by date(theDay) ");
    wxString maxusersql=_T("select sum(balance) as sumb, avg(balance) as avgb, min(balance) as minb, max(balance) as maxb from(");
    maxusersql+=expendsql+_T(")");
    wxLogDebug(_T("expendsql=%s"),expendsql);
    wxLogDebug(_T("maxusersql=%s"),maxusersql);
    ////////日常收支查询
    sqlite3_stmt *conMaxuser,*conExpend;
    if(sqlite3_prepare_v2(g_db,ToDefaultConv(expendsql),LenDefaultConv(expendsql),&conExpend,NULL)==SQLITE_OK) {
        int index1 = sqlite3_bind_parameter_index(conExpend, "@pa1");
        if(sqlite3_bind_text(conExpend, index1, ToDefaultConv(time_from), LenDefaultConv(time_from), SQLITE_STATIC)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conExpend, "@pa2");
        if(sqlite3_bind_text(conExpend, index1, ToDefaultConv(time_to), LenDefaultConv(time_to), SQLITE_STATIC)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on ntimeslot Error on. %s"), sqlite3_errmsg(g_db));
        }
        int row_count=0;
        while(sqlite3_step(conExpend)==SQLITE_ROW) {
            pList->InsertItem(row_count, _T(""));
            pList->SetItem(row_count,0,wxString((const char*)sqlite3_column_text(conExpend,0), DefaultConv));
            pList->SetItem(row_count++,1,wxString((const char*)sqlite3_column_text(conExpend,1), DefaultConv));
        }
    } else {
        wxLogDebug(_T("Error on sqlite3_prepare_v2: %s"), sqlite3_errmsg(g_db));
    }
    if (sqlite3_finalize(conExpend) != SQLITE_OK) {
        wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
    }
    //日常收支汇总
    wxString csStat;
    double sumexpend=0.,avgexpend=0.,minexpend=0.,maxexpend=0.;
    if(sqlite3_prepare_v2(g_db,ToDefaultConv(maxusersql),LenDefaultConv(maxusersql),&conMaxuser,NULL)==SQLITE_OK) {
        int index1 = sqlite3_bind_parameter_index(conMaxuser, "@pa1");
        if(sqlite3_bind_text(conMaxuser, index1, ToDefaultConv(time_from), LenDefaultConv(time_from), SQLITE_STATIC)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conMaxuser, "@pa2");
        if(sqlite3_bind_text(conMaxuser, index1, ToDefaultConv(time_to), LenDefaultConv(time_to), SQLITE_STATIC)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on ntimeslot Error on. %s"), sqlite3_errmsg(g_db));
        }
        if(sqlite3_step(conMaxuser)==SQLITE_ROW) {
            if(sqlite3_column_text(conMaxuser,0)!=NULL) {
                sumexpend=sqlite3_column_double(conMaxuser,0);
                avgexpend=sqlite3_column_double(conMaxuser,1);
                minexpend=sqlite3_column_double(conMaxuser,2);
                maxexpend=sqlite3_column_double(conMaxuser,3);
            }
        }
    } else {
        wxLogDebug(_T("Error on sqlite3_prepare_v2: %s"), sqlite3_errmsg(g_db));
    }
    if (sqlite3_finalize(conMaxuser) != SQLITE_OK) {
        wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
    }
    csStat=wxString::Format(_T("总收支%g,平均收支%g,最小收支%g,最大收支%g"),sumexpend,avgexpend,minexpend,maxexpend);
    pText=wxDynamicCast(FindWindowById(IDC_EDIT_STATIC),wxTextCtrl);
    pText->SetValue(csStat);
    wxLogDebug(_T("OnBnClickedBtnSearch"));
}

void CDlgReportDay::OnBnClickedBtnExit(wxCommandEvent& event)
{
    Close();
    wxLogDebug(_T("OnBnClickedBtnExit"));
}

void CDlgReportDay::ShowData()
{
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    int itemcount=pList->GetItemCount();
    if(itemcount<=0) {
        return;
    }
    double *data=new double[itemcount];
    time_t *times=new time_t[itemcount];
    wxDateTime dt=wxDateTime::Now();
    for (int n = 0; n < itemcount; n++) {
        dt.ParseDate(pList->GetItemText(n,0));
        pList->GetItemText(n,1).ToDouble(&data[n]);
        times[n] = dt.GetTicks();
    }
    TimeSeriesDataset *dataset = new TimeSeriesDataset(data, times, itemcount);
    DateAxis *bottomAxis = new DateAxis(AXIS_BOTTOM);
    bottomAxis->SetVerticalLabelText(true);
    bottomAxis->SetDateFormat(wxT("%Y-%m-%d"));

    // first step: create plot
    XYPlot *plot = new XYPlot();
    // create line renderer
    // set it to draw lines and symbols.
    XYLineRenderer *renderer = new XYLineRenderer(true, true);

    // we can change line pen for serie, for example set short-dash
    // line style and width=2 for third serie
    renderer->SetSeriePen(1, wxThePenList->FindOrCreatePen(*wxGREEN, 1, wxSOLID));
    dataset->SetRenderer(renderer);

    // add dataset to plot
    plot->AddDataset(dataset);

    // create left and bottom number axes
    NumberAxis *leftAxis = new NumberAxis(AXIS_LEFT);
    //leftAxis->SetFixedBounds(2*quota.dayp.minprice-quota.dayp.maxprice,2*quota.dayp.maxprice-quota.dayp.minprice);
    // add axes to plot
    plot->AddAxis(leftAxis);
    plot->AddAxis(bottomAxis);

    // link axes and dataset
    plot->LinkDataVerticalAxis(0, 0);
    plot->LinkDataHorizontalAxis(0, 0);

    // set legend
    //plot->SetLegend(new Legend(wxBOTTOM, wxCENTER));

    // and finally create chart
    Chart *chart = new Chart(plot, _T("趋势图"));
    chartpanel_->SetChart(chart);
    if(data){
        delete []data;
    }
    if(times){
        delete []times;
    }
}

void CDlgReportDay::OnTimer(wxTimerEvent& event)
{
    wxTimer& timer=event.GetTimer();
    if(timer.GetId()==IDC_TIMER_SEC) {
        ShowData();//显示数据
    }
}
